/*
 * $Id: SweepRequestAction.java,v 1.12 2009/10/06 19:01:23 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.ui.actions;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.database.dao.IRequestDefnDAO;
import com.ge.healthcare.autosc.common.util.ApplicationInfo;
import com.ge.healthcare.autosc.common.util.PropertyConstants;
import com.ge.healthcare.autosc.common.util.UtilizationLog;
import com.ge.healthcare.autosc.pss.request.PSSRequest;
import com.ge.healthcare.autosc.pss.response.PSSResponse;
import com.ge.healthcare.autosc.pssClient.TransportMgr;
import com.ge.med.service.eds.utilization.client.UtilizationException;

/**
 * @author 212042764
 * 
 */
public class SweepRequestAction {
	private static final String SWEEP_NAME = "sweepName";
	private static final String SYSTEM_IDS = "systemIdLst";
	private static final String SCHEDULED_DATE = "scheduledDate";
	private static final String SENT_FROM = "sentFrom";
	private static final String SSO = "sso";
	private static final String REQUIRES_MAIL = "requireMail";
	private static final String REPLY_T0_ADDRESSES = "replyToAddresses";
	private static final String XARGS = "xargs";
	private static final String SWEEP_FEATURE_NAME = "Util_SweepRequest";
	private static final String SWEEP_EVENT = "SweepRequest";

	public static IRequestDefnDAO requestDefnDAO = null;

	/**
	 * Method called from UI to populate modality and request defn lists
	 * 
	 * @return
	 */
	public static Map<String, List<String>> getRequestableRequestTypesPerModality() {
		return requestDefnDAO.getRequestableRequestTypesPerModality();
	}

	/**
	 * Submits PSS Request and returns PSS Response as returned by PSS Server
	 * The reason why am throwing throwable is because i would like to log any
	 * Error exceptions that may occur because of linkage errors as a result of
	 * spring + laszlo + weblogic integration
	 * 
	 * @param userInputHash
	 * @return
	 * @throws Exception
	 */
	public static PSSResponse sendPSSRequest(Hashtable<?, ?> userInputHash)
			throws Throwable {
		String methodName = "sendPSSRequest";
		UtilizationLog utilLog = null;
		try {
			utilLog = getUtilObject((String) userInputHash.get(SSO));
			logStartSessionEvent(utilLog);
			ASCLogger.info(SweepRequestAction.class, methodName,
					"Received user input hash:" + userInputHash);
			PSSRequest pssRequest = buildPSSRequest(userInputHash);
			pssRequest.setFromEmailAddress((String) userInputHash
					.get(SENT_FROM));
			pssRequest.setSentEmailNotifications((Boolean) userInputHash
					.get(REQUIRES_MAIL));
			pssRequest.setScheduledDate(getScheduledDate(userInputHash));
			pssRequest
					.setReplyToAddressLst(getReplyToAddressLst(userInputHash));
			pssRequest.setXargs(getXargs(userInputHash));
			ASCLogger.info(SweepRequestAction.class, methodName,
					"Sending request:" + pssRequest);
			PSSResponse pssResponse = TransportMgr.sendWsRequestToPssServer(
					pssRequest, getPSSWsURL());
			ASCLogger.info(SweepRequestAction.class, methodName,
					"Received Response:" + pssResponse);
			return pssResponse;
		} catch (Throwable exception) {
			ASCLogger.error(SweepRequestAction.class, methodName, exception
					.getMessage(), exception);
			throw exception;
		}
	}

	/**
	 * Gets xargs as entered by user
	 * 
	 * @param userInputHash
	 * @return
	 */
	private static String getXargs(Hashtable<?, ?> userInputHash) {
		String xargs = (String) userInputHash.get(XARGS);
		if (ASCUtil.isNullOrEmpty(xargs)) {
			return null;
		}
		return xargs.trim();
	}

	/**
	 * Figures the URL for PSS Server
	 * 
	 * @return
	 */
	private static String getPSSWsURL() {
		return ApplicationInfo.getInstance().getProperty(
				PropertyConstants.PSS_WS_URL);
	}

	/**
	 * Builts PSS Request object
	 * 
	 * @param userInputHash
	 * @return
	 */
	private static PSSRequest buildPSSRequest(Hashtable<?, ?> userInputHash) {
		PSSRequest pssRequest = new PSSRequest();
		pssRequest.setRequestType(((String) userInputHash.get(SWEEP_NAME))
				.trim());
		pssRequest.setSystemIdLst(getSystemIdLst(((String) userInputHash
				.get(SYSTEM_IDS)).trim()));
		return pssRequest;
	}

	/**
	 * Gets the scheduled date as choosen by user
	 * 
	 * @param userInputHash
	 * @return
	 */
	private static String getScheduledDate(Hashtable<?, ?> userInputHash) {
		String scheduledDate = (String) userInputHash.get(SCHEDULED_DATE);
		if (!ASCUtil.isNullOrEmpty(scheduledDate)) {
			return scheduledDate;
		}
		return null;
	}

	/**
	 * Converts system id list seperating on new line character
	 * 
	 * @param systemIds
	 * @return
	 */
	private static List<String> getSystemIdLst(String systemIds) {
		final String[] arrSystemId = systemIds.split("\n");
		List<String> systemIdLst = new ArrayList<String>();
		for (String systemId : arrSystemId) {
			systemIdLst.add(systemId);
		}
		return systemIdLst;
	}

	/**
	 * Returns list of reply to addresses
	 * 
	 * @param userInputHash
	 * @return
	 */
	private static List<String> getReplyToAddressLst(
			Hashtable<?, ?> userInputHash) {
		String replyToAddress = (String) userInputHash.get(REPLY_T0_ADDRESSES);
		if (ASCUtil.isNullOrEmpty(replyToAddress)) {
			return null;
		}
		final String[] replyToAddresses = replyToAddress.split(",");
		List<String> replyToAddressLst = new ArrayList<String>();
		for (String replyTo : replyToAddresses) {
			replyToAddressLst.add(replyTo.trim());
		}
		return replyToAddressLst;
	}

	/**
	 * @param requestDefnDAO
	 *            the requestDefnDAO to set
	 */
	public void setRequestDefnDAO(IRequestDefnDAO requestDefnDAO) {
		SweepRequestAction.requestDefnDAO = requestDefnDAO;
	}

	/**
	 * Creates the utilization object and initializes the global session for the
	 * same Uses StackIntroSpector to get the Caller method name In case you are
	 * wondering what this method is doing in the facade. This is here because
	 * ISDLogger is supposed to be used in this class only
	 * 
	 * @return
	 */
	private static UtilizationLog getUtilObject(String user) {
		try {
			return new UtilizationLog(SWEEP_FEATURE_NAME, user, "USER", "ASC",
					true);
		} catch (UtilizationException utilizationException) {
			ASCLogger.error(SweepRequestAction.class, "getUtilObject",
					"Failed to retrieve session id for performing utilization logging"
							+ utilizationException.getMessage());
			return null;
		}
	}

	/**
	 * Logs the Start session event In case you are wondering what this method
	 * is doing in the facade. This is here because ISDLogger is supposed to be
	 * used in this class only
	 * 
	 * @param utilizationLog
	 */
	private static void logStartSessionEvent(UtilizationLog utilizationLog) {
		if (utilizationLog != null) {
			try {
				utilizationLog.log("AutoSC Drag-ON Tool", "", SWEEP_EVENT, "");
			} catch (UtilizationException utilizationException) {
				ASCLogger.error(SweepRequestAction.class, "getUtilObject",
						"Failed to log the Utilization srart event"
								+ utilizationException.getMessage());
			}
		}
	}
}
